//
//  EFSelectTableMenu.m
//  MyCollectionView
//
//  Created by xinqing on 15/9/14.
//  Copyright (c) 2015年 pansoft. All rights reserved.
//

#import "EFSelectTableMenu.h"
#import "ViewControllerManager.h"
#import "Constant.h"
#import "MBProgressHUD.h"
#import "EFSelectTableMenuCell.h"
#import "Masonry.h"
#import "EnvironmentVariable.h"
#import "ThemeKit.h"

#define LAYOUT_HEIGHT 90
#define LAYOUT_WIDTH 50
#define SCROLL_DIRECTION UICollectionViewScrollDirectionVertical
#define PAGE_CONTROL_HEIGHT 10
#define SELECTED_KEY @"checked"

static NSString *tableCell = @"tableCell";

@interface EFSelectTableMenu(){
    
}

@property(nonatomic,strong) NSDictionary *checkDict;//plist

@end

@implementation EFSelectTableMenu
{
    UITableView *changeTable;
    UIColor *_backColor;
    BOOL isUnSaveToList;
}

-(instancetype)initWithData:(NSMutableArray *)stubObjects
{
    CGRect frame = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width , [[UIScreen mainScreen] bounds].size.height);
    self = [self initWithFrame:frame datas:stubObjects];
    return self;
}

-(instancetype)initWithFrame:(CGRect)frame datas:(NSMutableArray *) stubObjects{
    self = [super initWithFrame:frame];
    self.backgroundColor = [UIColor whiteColor];
    if (self) {
        _backColor = EF_RED_COLOR;
        isUnSaveToList = NO;
        self.items = stubObjects;
        //处理 “全选” 复选框
        [self manageAllSelectedCheckBox];
        [self setBackgroundColor:[UIColor clearColor]];
        
        changeTable = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width,  frame.size.height-50) style:UITableViewStylePlain];
        changeTable.dataSource = self;
        changeTable.delegate = self;
        changeTable.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        changeTable.bounces = NO;
        changeTable.tableFooterView = [UIView new];
        [changeTable registerClass:[EFSelectTableMenuCell class] forCellReuseIdentifier:tableCell];
        [self addSubview:changeTable];
        
        //保存按钮
        _saveButton = [UIButton buttonWithType:UIButtonTypeCustom];
        //指定button的位置和大小
        CGFloat saveButtonWidth = 300;
        CGFloat saveButtonHeight = 44;
        //给button设置标签，用来辨别点击的是哪个button，常用在委托方法中。
        _saveButton.tag = 0;
        //定义按钮标题
        [_saveButton setTitle:@"保存" forState:UIControlStateNormal];
        [_saveButton  setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [_saveButton setBackgroundColor:_backColor];
        //定义按钮标题字体格式
        [_saveButton.titleLabel setFont:[UIFont boldSystemFontOfSize:17]];
        //        [saveButton.titleLabel setTextColor:[UIColor blackColor]];
        //给button添加委托方法，即点击触发的事件。
        [_saveButton addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_saveButton];
        [_saveButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(self).with.offset(0);
            make.height.mas_equalTo(@50);
        }];
        [self createTheme];
    }
    return self;
}

-(void)createTheme {
    self.theme_backgroundColor = changeTable.theme_backgroundColor = [UIColor theme_colorForKey:@"viewBackgroud" ];
    changeTable.theme_separatorColor = [UIColor theme_colorForKey:@"separatorColor" ];
    
}

#pragma -mark 处理 “全选” 复选框
-(void)manageAllSelectedCheckBox{
    self.checkDict = [PlistUtil getPLlistDicWitName:@"ConfigMenu.plist"];
}

-(void)action:(id)sender{
    //这个sender其实就是UIButton，因此通过sender.tag就可以拿到刚才的参数
    NSInteger i = [sender tag];
    switch (i) {
        case 0:
            //plist存储数据
            NSLog(@"点击保存按钮");
            [self saveData];
            break;
        default:
            break;
    }
}

-(void)saveData{
    NSMutableDictionary *plistDict;
    if (_checkDict != nil && [_checkDict count] > 0) {
        if (isUnSaveToList == YES) {
            plistDict = [[NSMutableDictionary alloc ] init];
            for (StubObject *stub in _items) {
                [plistDict setObject:[stub getObjectForKey:SELECTED_KEY withDefaultValue:@"0"] forKey:[stub getID]];
            }
            //把之前的数据也要添加上
            [plistDict addEntriesFromDictionary:_checkDict];
        }else{
            plistDict = [NSMutableDictionary dictionaryWithDictionary:_checkDict];
        }
    }else{
        plistDict = [[NSMutableDictionary alloc ] init];
        for (StubObject *stub in _items) {
            [plistDict setObject:[stub getObjectForKey:SELECTED_KEY withDefaultValue:@"0"] forKey:[stub getID]];
        }
    }
    //写入文件
    [self saveData:plistDict toFile:@"ConfigMenu.plist"];
    [self showMBProgressHUDDialog];
    //发送通知
    [[NSNotificationCenter defaultCenter] postNotificationName:@"selectCollectionMenuNotification" object:plistDict];
    [ViewControllerManager popViewControllerAnimated:YES];
}

-(void)saveData:(NSMutableDictionary *)data toFile:(NSString *)fileName{
    //获取路径
    NSString *path = [PlistUtil getPathWithName:fileName];
    //写入文件
    [data writeToFile:path atomically:YES];
}

- (void)showMBProgressHUDDialog{
    MBProgressHUD *HUD = [[MBProgressHUD alloc] initWithView:self];
    [self addSubview:HUD];
    HUD.label.text = @"保存成功";
    HUD.mode = MBProgressHUDModeText;
    //指定距离中心点的X轴和Y轴的偏移量，如果不指定则在屏幕中间显示
    //HUD.yOffset = 150.0f;
    //HUD.xOffset = 100.0f;
    [HUD showAnimated:YES];
    [HUD hideAnimated:YES afterDelay:2];
//    [HUD showAnimated:YES whileExecutingBlock:^{
//        sleep(2);
//    } completionBlock:^{
//        [HUD removeFromSuperview];
//    }];
}

#pragma mark - tableView
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _items.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    EFSelectTableMenuCell * cell = [tableView dequeueReusableCellWithIdentifier:tableCell forIndexPath:indexPath];
    cell.delegate = self;
    
    StubObject *currentStubObject = [_items objectAtIndex:indexPath.row];
    [cell titleImagePath:[currentStubObject getStringForKey:@"menuIcon" withDefaultValue:@"title"]];
    cell.title.text = [currentStubObject getStringForKey:@"caption" withDefaultValue:@"title"];
    BOOL isChecked = [self itemIsChecked:currentStubObject];
    if (isChecked) {
        [cell.addOrRemove setTitle:@"移除" forState:UIControlStateNormal];
        [cell.addOrRemove setBackgroundColor:[UIColor whiteColor]];
        [cell.addOrRemove setTitleColor:EF_RED_COLOR forState:UIControlStateNormal];
    }else{
        [cell.addOrRemove setTitle:@"添加" forState:UIControlStateNormal];
        [cell.addOrRemove setBackgroundColor:EF_RED_COLOR];
        [cell.addOrRemove setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    //如果是“更多”，隐藏cell
    NSString *viewType = [currentStubObject getStringForKey:@"viewType" withDefaultValue:@""];
    if ([viewType isEqualToString:@"menuMore"]) {
        [cell setHidden:YES];
    }else{
        [cell setHidden:NO];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60;
}

#pragma mark cellDelegate
- (void)clickAddOrRemoveButton:(EFSelectTableMenuCell *)cell{
    NSIndexPath *index = [changeTable indexPathForCell:cell];
    StubObject *stub = [_items objectAtIndex:index.row];
    BOOL checked;
    if (isUnSaveToList == YES || _checkDict ==nil) {
        checked = [[stub getStringForKey:SELECTED_KEY withDefaultValue:@"0"] boolValue];
    }else{
        checked = [[_checkDict objectForKey:[stub getID]] boolValue];
    }
    if (checked) {
        [stub setString:@"0" forAKey:SELECTED_KEY];
        [_checkDict setValue:@"0" forKey:[stub getID]];
        
        [cell.addOrRemove setBackgroundColor:EF_RED_COLOR];
        [cell.addOrRemove setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cell.addOrRemove setTitle:@"添加" forState:UIControlStateNormal];
    }else{
        [stub setString:@"1" forAKey:SELECTED_KEY];
        [_checkDict setValue:@"1" forKey:[stub getID]];
        
        [cell.addOrRemove setBackgroundColor:[UIColor whiteColor]];
        [cell.addOrRemove setTitleColor:EF_RED_COLOR forState:UIControlStateNormal];
        [cell.addOrRemove setTitle:@"移除" forState:UIControlStateNormal];
    }
}

#pragma -mark 判断checked
-(BOOL)itemIsChecked:(StubObject *)stubObject{
    //if plist 有值，从 plist 读取数据 else 从 stubObject 中读取数据
    BOOL isChecked;
    if(_checkDict != nil && _checkDict.count >0){
        NSString *isCheckedStr = [_checkDict objectForKey:[stubObject getID]];
        if (isCheckedStr != nil) {
            isChecked = [isCheckedStr boolValue];
        }else{
            isUnSaveToList = YES;
            isChecked = [[stubObject getStringForKey:SELECTED_KEY withDefaultValue:@"0"] boolValue];
        }
    }else{
        isChecked = [[stubObject getStringForKey:SELECTED_KEY withDefaultValue:@"0"] boolValue];
    }
    return isChecked;
}

#pragma -mark selectAll
-(void)selectAll{
    for (StubObject *stub in _items) {
        [stub setString:@"1" forAKey:SELECTED_KEY];
        [_checkDict setValue:@"1" forKey:[stub getID]];
        
    }
}

#pragma -mark deselectAll
-(void)deselectAll{
    for (StubObject *stub in _items) {
        [stub setString:@"0" forAKey:SELECTED_KEY];
        [_checkDict setValue:@"0" forKey:[stub getID]];
    }
}

-(void)reloadData{
    [changeTable reloadData];
}

@end
